//
//  ios_Image.mm
//  Prism
//
//  Created by Bas du Pre on 20-05-11.
//  Copyright 2011 UU. All rights reserved.
//

// iOS specific implementation

#include "global.h"
#if PRISM_OS_IOS
#include "ios_global.h"

#include "Texture.h"

#include <iostream>

void Prism::Texture::native_init() {
    native_cachedTexture = 0;
}

CCTexture2D* Prism::Texture::native_toCCTexture2D() {
    if (file()->filename() == native_cachedTextureFilename)
        return native_cachedTexture;
    
    NSString *filename = [NSString stringWithUTF8String: file()->filename()];
    PRISM_LOGINFO("Loading texture: %s", [filename UTF8String]);
    
    if ([[CCDirector sharedDirector] contentScaleFactor] == 2.0) {
        // check whether there is a highres version of the image	
        NSString* ext = [filename pathExtension];
        NSString* p = [filename stringByDeletingPathExtension];
        NSString* highres = [NSString stringWithFormat:@"%@@2x.%@", p, ext];
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:highres]) {
            PRISM_LOGINFO("  > found high-res replacement: %s", [highres UTF8String]);
            load([highres cStringUsingEncoding:[NSString defaultCStringEncoding]]);
            filename = highres;
        }
    }

    native_cachedTextureFilename = file()->filename();
    native_cachedTexture = [[CCTextureCache sharedTextureCache] addImage:filename];
    [native_cachedTexture setAliasTexParameters];
    // TODO: set alias shit
    
    return native_cachedTexture;
}

Prism::Size Prism::Texture::native_size() {    
    Prism::Size size;
    if (native_cachedTexture == 0)
        native_toCCTexture2D(); // force loading of texture2d
    CGSize cgsize = [native_cachedTexture contentSizeInPixels];

    size.width = cgsize.width;
    size.height = cgsize.height;
    
    return size;
}


#endif